<template>
  <el-dialog
    :title="lang.t('common.create')"
    v-model="show"
    :width="500"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="plugin.lang('voucher.money')" prop="money">
            <div style="width: 100%; overflow: hidden; text-align:left">
              <el-input-number 
                ref="input"
                v-model="form.money" 
                @focus="(e) => e.target.select()" 
                @keyup.enter="onCreate"
                :min="0.01" 
                :precision="2" 
                style="width: 100%" 
                controls-position="right" 
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="plugin.lang('voucher.expire_time')" prop="expire_time">
            <div style="width: 100%; overflow: hidden">
              <Date v-model="form.expire_time" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="plugin.lang('voucher.log.remarks')" prop="remarks">
        <el-input v-model="form.remarks" @keyup.enter="onCreate"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" style="width: 100%" :loading="loading" @click="onCreate">{{ lang.t('common.create') }}</el-button>
  </el-dialog>
</template>
<script>
import { ref, nextTick } from 'vue'
import app from '@/app'
import voucherModel from '../../model/voucher'

import Date from '@/components/date'

export default {
  components: {
    Date
  },
  setup() {
    // 插件
    const plugin = app.plugin.index

    // 对话框
    const show = ref(false)

    // 表单
    const formRef = ref(null)

    // 默认表单类型
    const form = ref({})

    // 金额输入框
    const input = ref(null)

    // 验证
    const rules = {
      money: [
        { required: true, message: ' ', trigger: 'blur' }
      ]
    }

    // 打开
    const open = async(data) => {
      // 定义代金劵类型
      form.value = Object.assign({ type: 1 }, data)
      show.value = true
      // 金额
      if(!parseFloat(form.value.money)) {
        form.value.money = 1
      }

      // 自动焦点
      await nextTick()
      input.value.focus()
    }

    // 更新
    const loading = ref(false)
    const onCreate = () => {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true
          // 如果有过期时间，将延长到23:59
          if(form.value.expire_time) {
            form.value.expire_time += 86399
          }
          
          voucherModel.create(form.value).then(() => {
            // 更新列表
            show.value = false
          }).finally(() => {
            loading.value = false
          })
        }
      })
    }

    return {
      lang: app.lang,
      plugin,
      show,
      open,
      voucherModel,
      formRef,
      form,
      input,
      rules,
      loading,
      onCreate, 
    }
  }
}
</script>